package com.pay.weixin.util;


import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by ThreeManTeam on 2016/11/14.
 */
public class HttpUtil {

    //private static final Log logger = Logs.get();
    private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
    private final static String DEFAULT_ENCODING = "UTF-8";

    public static String postData(String urlStr, String data){
        return postData(urlStr, data, null);
    }

    public static String postData(String urlStr, String data, String contentType){
        BufferedReader reader = null;
        try {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(CONNECT_TIMEOUT);
            if(contentType != null)
                conn.setRequestProperty("content-type", contentType);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
            if(data == null)
                data = "";
            writer.write(data);
            writer.flush();
            writer.close();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\r\n");
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error connecting to " + urlStr + ": " + e.getMessage());
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
            }
        }
        return null;
    }

    public static String postDataEx(String urlStr, String data){
        String result = "";
        try{
            StringEntity entity = new StringEntity(data, "UTF-8");//解决中文乱码问题
            entity.setContentEncoding("UTF-8");
            HttpClientHelper helper = HttpClientHelper.getHttpClientInstance();
            HttpPost httpPost =  new HttpPost(urlStr);

            httpPost.setEntity(entity);

            CloseableHttpResponse response = null;

            //执行请求
            response = helper.getHttpClient().execute(httpPost);
            try {
                //获得响应的消息实体
                HttpEntity entity1 = response.getEntity();
                try {
                    //获取响应状态码
                    int statusCode = response.getStatusLine().getStatusCode();
                    //根据响应状态码进行处理
                    switch (statusCode) {
                        case 200:
                            byte[] contentBytes = EntityUtils.toByteArray(entity1);
                            result = new String(contentBytes, "UTF-8");
                            break;
                        default:
                            String info = String.format("执行失败(请求结果码：%s", statusCode);
                            break;
                    }
                } finally {
                    //关闭httpEntity流
                    EntityUtils.consume(entity1);
                }
            }finally {
                if (response != null)
                    response.close();
            }
        }catch (Exception ex){
            String info = String.format("执行异常：%s", ex.getMessage());
        }

        return result;
    }
}